package util.utilitarioXML;

import Entidades.Address;
import Entidades.Client;
import Entidades.Hardware;
import Entidades.Item;
import Entidades.Orderes;
import Entidades.Product;
import Entidades.Software;
import Entidades.Supply;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class XMLParser extends DefaultHandler {

    static private Writer out;
    private Orderes p = new Orderes();
    private Client c;
    private List<Item> itens;

    public XMLParser() {
    }

    public static Orderes parser(File arqXML) {

        return parser(arqXML, new InputSource("C:\\WebApplication\\src\\java\\config\\tmp\\pedido.xml"));
    }

    public static Orderes parser(File arqXML, InputSource dtd) {

        // Use uma instancia de XMLParser como o SAX EventHandler
        XMLParser handler = new XMLParser();

        // Usa o parser SAX  default (sem validação)
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(true);
        factory.setNamespaceAware(true);

        try {
            // Configura a saida
            out = new OutputStreamWriter(System.out, "UTF8");
            // Processa a entrada
            SAXParser saxParser = factory.newSAXParser();

            XMLReader reader = saxParser.getXMLReader();
            reader.setErrorHandler(new SimpleErrorHandler());
            reader.parse(dtd);
            saxParser.parse(arqXML, handler);
        }
        catch (ParserConfigurationException | SAXException | IOException t) {
        }
        
        return handler.getOrderes();
    }
    
    public Orderes getOrderes() {
        return p;
    }
    
    /*
     * A seguir temos as implementação dos métodos startdocument, enddocument, starelement e endelement definidos na interface DefaultHandler.
     */
    @Override
    public void startDocument()
            throws SAXException {
    }

    @Override
    public void endDocument()
            throws SAXException {
    }

    @Override
    public void startElement(String namespaceURI,
            String sName, // simple name (localName)
            String qName, // qualified name
            Attributes attrs)
            throws SAXException {
        switch (qName) {
            case "pedido":
                p.setNumber(Integer.parseInt(attrs.getValue("number")));
                itens = new ArrayList<>();
                p.setItem(itens);
                break;
            case "cliente":
                c = new Client();
                c.setId(Integer.parseInt(attrs.getValue("custumerID")));
                c.setName(attrs.getValue("name"));
                p.setClient(c);
                break;
            case "itemdeLinha":
                Item i = new Item();
                i.setQuanttity(Integer.parseInt(attrs.getValue("quantity")));
                itens.add(i);
                break;
            case "produto":
                Product p;
                if (attrs.getValue("type").toLowerCase().equals("software")) {
                    p = new Software();
                    ((Software) p).setVersion((attrs.getValue("version")));
                }
                else {
                    p = new Hardware();
                    ((Hardware) p).setAssembly(attrs.getValue("assembly"));
                }
                p.setDescription(attrs.getValue("description"));
                p.setPrice(Double.parseDouble(attrs.getValue("unitPrice")));
              //  p.setSupply(new ArrayList<Supply>());  >> acertar este metodo
                itens.get(itens.size() - 1).setProduct(p);
                break;
            case "fornecedor":
                Supply f = new Supply();
                f.setNumer(Integer.parseInt(attrs.getValue("number")));
                //itens.get(itens.size() - 1).getProduct().setSupply(f); >> acertar este metodo
                break;
            case "endereco":
                Address e = new Address();

                e.setStreet(attrs.getValue("street"));
                e.setPostalCode(attrs.getValue("postalCode"));
                e.setCity(attrs.getValue("city"));
                e.setContry(attrs.getValue("country"));
                e.setStateORprovince(attrs.getValue("stateProvince"));

                if (c.getAddress() == null) {
                    c.setAddress(e);
                }
                else {
                   // List<Supply> fornecedores = itens.get(itens.size() - 1).getProduct().getSupply(); >> acertar este metodo
                    //fornecedores.get(fornecedores.size() - 1).setAddress(e);
                }
                break;
        }
    }

    @Override
    public void endElement(String namespaceURI,
            String sName, // simple name
            String qName // qualified name
            )
            throws SAXException {
    }

    @Override
    public void characters(char buf[], int offset, int len)
            throws SAXException {
    }

}
